<template>
    <div class="content">
        <!-- 控件 -->
        <template>
            <div class="control" style="margin-top: 20px; width: 70%;margin: 30px auto;display: flex ; justify-content: flex-end;">
                <el-button type="primary" size="mini" @click="handleOpen">新 增</el-button>
                <el-button type="primary" size="mini" @click="handleSubmitForm">保 存</el-button>
                <el-button type="primary" size="mini" @click="handleCancel" plain>关 闭</el-button>
            </div>
        </template>
        <!-- 内容 -->
        <div class="content_form">
            <el-form ref="form" :model="form" :rules="rules" label-width="7.5rem">
                <div>
                    <h1 class="title" style="color: #606266;font-weight: 600;">{{ questionnaireName }}专项学习</h1>
                    <h1 class="title" style="font-size: .875rem;color: #909399;">本题共100分</h1>
                    <ul id="topic">
                        <li class="topic_li" v-for="(item, index ) in listOfTopics">
                            <div class="topic_li_p">
                                <p>
                                    {{ item.topicName }}( )
                                    <span class="topic_li_p_span">本题{{ item.topicScore }}分</span>
                                </p>
                                <div>
                                    <i @click="handleTopicsD(index)" style="color: #F56C6C;" class="el-icon-delete"></i>
                                    <el-divider direction="vertical"></el-divider>
                                    <i @click="handleTopicsX(index)" style="color: #67C23A;" class="el-icon-edit"></i>
                                </div>

                            </div>
                            <ol class="topic_li_ol">
                                <li class="topic_li_ol_li" v-for="a in item.AnswerList">
                                    <span class="topic_li_ol_li_span1">{{ a.option }}</span>
                                    <span class="topic_li_ol_li_span2">本答案{{ a.score }}分</span>
                                </li>
                            </ol>

                        </li>
                    </ul>

                </div>



            </el-form>
        </div>
        <!-- 添加或修改项目管理指标对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
            <el-form ref="formFormIndex" :model="formIndex" :rules="rulesFormIndex" label-width="7.5rem">
                <el-form-item label="题目名称:" prop="topicName">
                    <el-input v-model="formIndex.topicName" placeholder="请输入题目名称" />
                </el-form-item>

                <el-form-item label="分值:" prop="topicScore">

                    <el-input v-model="formIndex.topicScore" placeholder="请输入分值"
                        oninput="this.value = this.value.replace(/[^\d]/g, '')">
                        <template slot="prepend"><span style="color: red;font-size: .75rem;">分值剩余{{ residue
                                }}</span></template>
                    </el-input>
                </el-form-item>


                <el-row v-for="(item, index) in formIndex.AnswerList">
                    <el-col :span="12">
                        <el-form-item :label='`${item.optionName}${index + 1}:`'>
                            <el-input @input="$forceUpdate()" v-model='item.option' placeholder="请输入选项" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label='`${item.scoreName}${index + 1}:`'>
                            <el-input @input="$forceUpdate()" v-model='item.score' placeholder="请输入选项分值"
                                oninput="this.value = this.value.replace(/[^\d]/g, '')" />
                        </el-form-item>
                    </el-col>

                </el-row>
                <div class="plus">
                    <el-button @click="handelPus" type="primary" round plain><i class="el-icon-plus"></i></el-button>

                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="submitForm" :disabled="residue == 0">确 定</el-button>
                <el-button size="mini" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>

// import { addInfoQuestionNaire, updateInfoQuestionNaire, getInfoQuestionNaire } from "../../api/InfoQuestionNaire/infoQuestionNaire"
import { listNaire, getNaire, delNaire, addNaire, updateNaire } from "@/api/InfoQuestionNaire/naire";

export default {
    components: {


    },
    beforeRouteEnter(to, from, next) {
        if (to.query.ids) {
            to.meta.title = "题修改"
        } else {
            to.meta.title = "题添加"
        }
        next()
    },
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入分值'));
            } else {
                if (value > this.residue) {
                    callback(new Error('分值不能超过总分值'));

                }
                callback();
            }
        };
        return {
            // 答案总数
            totalnum: 2,
            // 题目列表
            listOfTopics: [],
            // 分值剩余
            residue: 100,
            // 项目id
            projectId: null,
            // 合并单位
            mergeArr: ['targetOne', 'targetTwo'],
            // 表单数据
            form: {



            },
            // 指标
            formIndex: {
                AnswerList: [
                    {
                        option: null,
                        score: null,
                        optionName: "选项",
                        scoreName: "分值",
                        selectedId: 0



                    }
                ]
            },
            // 是否显示弹出层
            open: false,
            // 挑选指标库弹
            open2: false,
            title: "",
            deptOptions: [],

            // 校验
            rules: {

            },
            indexTip: null,
            // 指标校验
            rulesFormIndex: {
                topicName: [
                    { required: true, message: '题目不能为空', trigger: 'change' }
                ],
                topicScore: [
                    { required: true, message: '分值不能为空', trigger: 'change' },
                    { validator: validatePass, trigger: 'blur' }
                ]
            },
            questionnaireName: null

        }
    },
    created() {
        this.projectId = this.$route.query.ids
        /**点击修改时,查询详情 */
        if (this.$route.query.ids) {
            getNaire(this.$route.query.ids).then(res => {
                this.questionnaireName = res.data.questionTitle
                this.listOfTopics = JSON.parse(res.data.questionContent)
            })

        } else {
            this.questionnaireName = this.$route.query.name

        }
    },
    mounted() {



    },
    methods: {
        /** 删除题目 */
        handleTopicsD(index) {
            this.$confirm('是否删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.listOfTopics.splice(index, 1)
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            })
        },
        /** 修改题目 */
        handleTopicsX(index) {
            this.indexTip = index
            this.title = "修改题目"
            this.open = true
            this.formIndex = JSON.parse(JSON.stringify(this.listOfTopics[index]))
            this.residue = 100
            this.open = true
            this.listOfTopics.forEach(item => {
                this.residue -= Number(item.topicScore)
            })
            this.residue += Number(this.formIndex.topicScore)
        },
        /** 新增 */
        handleOpen() {
            this.title = "添加题目"
            this.indexTip = null
            this.formIndex = {
                AnswerList: [
                    {
                        option: null,
                        score: null,
                        optionName: "选项",
                        scoreName: "分值",
                        selectedId: 0


                    }
                ]
            }
            this.residue = 100
            this.open = true
            this.listOfTopics.forEach(item => {
                this.residue -= Number(item.topicScore)
            })
            if (this.residue != 100) {
                this.$refs["formFormIndex"].resetFields()

            }

        },
        /** 添加选项 */
        handelPus() {
            let obj = {
                option: null,
                score: null,
                optionName: "选项",
                scoreName: "分值",
                selectedId: 0
            }
            this.formIndex.AnswerList.push({ ...obj, selectedId: this.formIndex.AnswerList.length })

        },

        /**  整体提交*/
        handleSubmitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let zong = 0
                    this.listOfTopics.forEach(item => {
                        zong += Number(item.topicScore)
                    })
                    if (zong != 100) {
                        this.$message.error('请检查题分值综合是否为100分');
                        return
                    }
                    // 如果有id时为修改没有时为新增
                    if (this.projectId == null) {
                        let data = {
                            totalScore:100,
                            questionTitle: this.questionnaireName,
                            questionContent: JSON.stringify(this.listOfTopics)
                        }
                        addNaire(data).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.$router.back()
                        });
                    } else {
                        let data = {
                            id: this.projectId,
                            qustionTitle: this.questionnaireName,
                            questionContent: JSON.stringify(this.listOfTopics)
                        }
                        updateNaire(data).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.$router.back()

                        });
                    }
                } else {
                    console.log("error submit!!");
                    //当验证失败跳转到空白的所在区域
                    this.$nextTick(() => {
                        let isError = document.getElementsByClassName("is-error");
                        isError[0] && isError[0].scrollIntoView({
                            // 滚动到指定节点
                            // 值有start,center,end，nearest
                            block: "center",
                            // 值有auto、instant,smooth，缓动动画
                            behavior: "smooth",
                        });
                    });
                    return false;
                }
            });
        },
        /** 关闭 */
        handleCancel() {
            this.$router.back()
        },
        /** 选择时间回调*/
        handleChangTime(e) {
            this.form.projectBeginTime = e[0]
            this.form.projectEndTime = e[0]
        },
        /** 指标提交按钮 */
        submitForm() {
            this.$refs["formFormIndex"].validate(valid => {
                if (valid) {
                    let IsTrue = true
                    let MaxFS = 0
                    for (let i = 0; i < this.formIndex.AnswerList.length; i++) {
                        if (!this.formIndex.AnswerList[i].option) {
                            // IsTrue = false
                            // break
                            this.$message.error('选项与分值不能为空，请检查');
                            return
                        }
                        if (!this.formIndex.AnswerList[i].score) {
                            IsTrue = false
                            this.$message.error('请填写选项分值');
                            return

                        }
                        console.log(Number(this.formIndex.AnswerList[i].score), i + "次")
                        console.log(Number(this.formIndex.AnswerList[i].score), Number(this.formIndex.topicScore), "111")
                        if (Number(this.formIndex.AnswerList[i].score) > Number(this.formIndex.topicScore)) {
                            this.$message.error('选项分值不能大于题目总分值');
                            return

                        }
                        if (this.formIndex.AnswerList[i].score == this.formIndex.topicScore) {
                            MaxFS += 1


                        }

                    }
                    // if (!IsTrue) {
                    //     this.$message.error('选项与分值不能为空，请检查');
                    //     return
                    // }
                    if (MaxFS == 0) {
                        this.$message.error('该题目选项中应有一个满分选项');
                        return
                    }
                    if (this.indexTip != null) {
                        this.listOfTopics.splice(this.indexTip, 1, JSON.parse(JSON.stringify({ ...this.formIndex })))
                        this.open = false;
                        this.$modal.msgSuccess("修改成功");
                    } else {

                        this.listOfTopics.push(JSON.parse(JSON.stringify({ ...this.formIndex })))
                        this.open = false;
                        this.$modal.msgSuccess("添加成功");

                    }
                }
            });
        },
        /** 指标取消按钮*/
        cancel() {
            this.open = false;
            this.reset();
        },




        // 表单重置
        reset() {
            this.form = {
                id: null,
                projectName: null,
                projectType: null,
                projectZhuGuanDeptName: null,
                projectZhuGuanDeptId: null,
                projectBeginTime: null,
                projectEndTime: null,
                projectImplementName: null,
                projectImplementId: null,
                projectYearSumMoney: null,
                projectZhongYangMoney: null,
                projectShengJiMoney: null,
                projectYearTarget: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };
            this.resetForm("form");
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep #topic::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    display: none;

}

.content_form {
    padding-left: 252px;
    padding-right: 252px;

    .el-form {
        border: 1px solid rgba($color: #006FBF, $alpha: .15);
        border-radius: 3px;
        padding: 10px 100px;
        height: 75vh;

    }
}

#topic {
    overflow-y: auto;
    height: 65vh;


    .topic_li {
        list-style: decimal;
        padding: 1.875rem 0;

        .topic_li_p {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #606266;
            font-weight: 500;

            .topic_li_p_span {
                font-size: .75rem;
                color: #909399;
                margin-left: .625rem;
            }

        }

        .topic_li_ol {
            display: flex;
            justify-content: flex-start;
            flex-wrap: wrap;

            .topic_li_ol_li {
                list-style: upper-alpha;
                min-width: 12.5rem;
                // width: 100%;
                padding-right: 12.5rem;
                margin: .625rem 0;



                .topic_li_ol_li_span1 {
                    color: #606266;

                }

                font-size: .875rem;
                color: #333;

                .topic_li_ol_li_span2 {
                    font-size: .75rem;
                    color: #909399;
                    margin-left: .625rem;
                }
            }

        }
    }
}

.plus {
    display: flex;
    justify-content: center;
}
</style>